<?php
class XmemberController extends Zend_Controller_Action
{
	private $_uiVar = array();
	private $_member;
	
	public function init()
	{
		$this->_uiVar["html"]["title"] = STE_Html::WEBSITE_TITLE;
		
		try
		{
			$db = Zend_Registry::get("DB");
			$this->_member = new STE_Member($db);
		}
		catch (Exception $ex)
		{
			echo $ex->getMessage();
		}
	}
	
	function loginAction()
	{
		$adminSession = new Zend_Session_Namespace("STE_ADMIN");
		if ((!isset($adminSession->member["IS_LOGIN"])) || ($adminSession->member["IS_LOGIN"] == 0))
		{
			if ($this->getRequest()->isPost())
			{
				$formData = $_POST;
				$formData = $this->_trimLoginData($formData);
				
				$errorMessage = $this->_checkLoginData($formData);
				if (empty($errorMessage))
				{
					$member = $this->_member->checkLogin($formData["email"], $formData["password"]);
					if ($member !== false)
					{
						$adminSession->member["ID"] = $member["ID"];
						$adminSession->member["FULLNAME"] = $member["FULLNAME"];
						$adminSession->member["EMAIL"] = $member["EMAIL"];
						$adminSession->member["IS_LOGIN"] = 1;
						
						echo json_encode(array("code" => 0, "data" => ""));
					}
					else
						echo json_encode(array("code" => -98, "data" => "- Thông tin đăng nhập không hợp lệ, vui lòng kiểm tra lại. <br />"));
				}
				else
					echo json_encode(array("code" => -99, "data" => $errorMessage));
			}
			else
			{
				$smarty = Zend_Registry::get("SMARTY");
				$smarty->assign("uiVar", $this->_uiVar);
				$smarty->display("x/member/login.tpl");
			}
		}
		else
		{
			if ((isset($adminSession->redirect["NEXT_URL"])) && (!empty($adminSession->redirect["NEXT_URL"])))
				header("Location: " . $adminSession->redirect["NEXT_URL"]);
			else
				header("Location: /xoverview");
		}
	}
	
	function logoutAction()
	{
		$adminSession = new Zend_Session_Namespace("STE_ADMIN");
		$adminSession->member = array();
		header("Location: /x");
	}
	
	function profileAction()
	{
	}
	
	private function _trimLoginData($formData)
	{
		$formData["email"] = trim($formData["email"]);
		return $formData;
	}
	
	private function _checkLoginData($formData)
	{
		$errorMessage = "";
		
		if (empty($formData["email"]) || empty($formData["password"]))
			$errorMessage = "- Vui lòng nhập vào các thông tin bắt buộc. <br />";
		
		return $errorMessage;
	}
}
?>